package com.haifeng.asms.api.aop;

import cn.hutool.http.HttpStatus;
import com.haifeng.asms.commons.exception.ValidException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

/**
 * <p>
 * 参数校验Aop
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-23
 */
@Slf4j
@Aspect
@Component
public class ParamValidAop implements Ordered {

    @Before("execution(public * com.haifeng.asms.api.controller..*(..))")
    public void doBefore(JoinPoint joinPoint) throws ValidException {
        // 校验参数
        for (Object arg : joinPoint.getArgs()) {
            if (arg instanceof BindingResult) {
                BindingResult result = (BindingResult) arg;
                if (result.hasErrors()) {
                    String defaultMessage = result.getFieldError().getDefaultMessage();
                    log.error("参数校验异常 -> [{}]：{}", defaultMessage, result.getTarget());
                    throw new ValidException(HttpStatus.HTTP_BAD_REQUEST, defaultMessage);
                }
            }
        }
    }

    @Override
    public int getOrder() {
        return 104;
    }
}
